package com.youlai.eng.common;

import com.youlai.common.base.PageBean;
import com.youlai.eng.entity.EngItemEntity;
import com.youlai.eng.query.PageQuery;
import com.youlai.eng.repository.EngItemRepository;
import com.youlai.common.result.PageResult;
import com.youlai.common.result.Result;
import com.youlai.utils.DateUtils;
import com.youlai.system.util.SecurityUtils;
import com.youlai.core.security.model.SysUserDetails;
import com.youlai.system.service.SysDictService;
import jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.Query;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BaseService<T extends BaseJpaEntity,S extends JpaRepository<T,Long> > {

    S repository;

    @PersistenceContext
    private EntityManager em;
    public EntityManager getEntityManager() {
        return em;
    }

    @Resource
    SysDictService sysDictService;

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public PageResult<T> getPageByHql(PageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        String keywords = queryParams.getKeywords();

        // 动态拼接sql
        String hql = "from EngBill2Entity where  deleted = 0  ";
        if (StringUtils.isNotEmpty(keywords)  ) {
            hql += " and (" +
                    " parentItemNo like '%" + keywords +"%' " +
                    " or childItemNo like '%" + keywords +"%' " +
                    ") ";
        }
        DateUtils.toDatabaseFormat(queryParams, "startUpdateTime", "endUpdateTime");
        if (StringUtils.isNotEmpty(queryParams.getStartUpdateTime())) {
            hql += " and DATE_FORMAT(updateTime, '%Y-%m-%d %H:%i:%s') >=  '"+ queryParams.getStartUpdateTime()  +"'  ";
        }
        if (StringUtils.isNotEmpty(queryParams.getEndUpdateTime())) {
            hql += " and DATE_FORMAT(updateTime, '%Y-%m-%d %H:%i:%s') <=  '"+ queryParams.getEndUpdateTime()  +"'  ";
        }

        // 查询数据
        PageBean pageBean = new PageBean();
        pageBean.setPage(pageNum);
        pageBean.setRows(pageSize);
        if(pageBean !=null && pageBean.isPagination()) {
            String countHql = getCountHql(hql);
            Query countQuery = em.createQuery(countHql);
            pageBean.setTotal(countQuery.getSingleResult().toString());

            hql += " order by  updateTime desc";
            Query query = em.createQuery(hql);
            query.setFirstResult(pageBean.getStartIndex());
            query.setMaxResults(pageBean.getRows());
            List<T> list = query.getResultList();
            PageResult page = PageResult.success(list, pageBean.getTotal());
            return page;
        }
        return null;
    }

    /**
     * 分页查询列表
     *
     * @param queryParams
     * @return
     */
    public Result<T> getListByHql(PageQuery queryParams) {
        // 动态拼接sql
        String hql = "from EngBill2Entity where  deleted = 0  ";
        // 查询参数
        String keywords = queryParams.getKeywords();
        if (StringUtils.isNotEmpty(keywords)  ) {
            hql += " and (" +
                    " parentItemNo like '%" + keywords +"%' " +
                    " or childItemNo like '%" + keywords +"%' " +
                    ") ";
        }
        Query query = em.createQuery(hql);
        query.setFirstResult(0);
        query.setMaxResults(10);
        List<T> list = query.getResultList();
        Result page = Result.success(list);
        return page;
    }

    public String getCountHql(String hql) {
        //hql = "from Book where bookName like :bookName"
        //hql = " select * from new Book where(bid,bookName) where bookName like :bookName"
        int index = hql.toUpperCase().indexOf("FROM");
        return "select count(1) " +hql.substring(index);
    }

    public void save(T entity){
        SysUserDetails user = SecurityUtils.getUser();
        entity.setCreateBy(user.getUserId());
        entity.setCreateName(user.getUsername());
        entity.setUpdateBy(user.getUserId());
        entity.setUpdateName(user.getUsername());
        entity.setStatus(0);
        repository.save(entity);
    }

    @Autowired
    private EngItemRepository engItemRepository;

    public void update(T entity){
        //处理审批的问题
        SysUserDetails user = SecurityUtils.getUser();
        entity.setUpdateBy(user.getUserId());
        entity.setUpdateName(user.getUsername());
        repository.save(entity);
    }

//    public T findById(Long id){
//        T entity = em.find(EngItemEntity.class, id);
//        if(entity!=null) {
//            return entity;
//        }
//        return null;
//    }

    public List<T> findListBy(String hql){
        Query query = em.createQuery(hql);
        List<T> list = query.getResultList();
        return list;
    }

    public Boolean deleteAllById(String idStrs){
        SysUserDetails user = SecurityUtils.getUser();
        // 逻辑删除
        List<Long> ids = Arrays.asList(idStrs.split(",")).stream()
                .map(idStr -> Long.parseLong(idStr)).collect(Collectors.toList());
        for(Long id:ids) {
            EngItemEntity entity = em.find(EngItemEntity.class, id);
            if(entity!=null) {
                entity.setDeleted(1);
                entity.setUpdateBy(user.getUserId());
                entity.setUpdateName(user.getUsername());
                em.merge(entity);
            }
        }
        return true;
    }

}


